<template>
  <!-- 查询选项 - 行政区 or 实体名称 -->
  <div
    v-if="visible"
    class="gis-search position-right"
    :class="{
      'top-margin': topMargin,
    }"
    @click.stop="UpSysPanel()"
  >
    <div class="search-box">
      <a-input-search
        v-model="searchKey"
        :placeholder="searchType === 'area' ? '请输入行政区' : '请输入实体名'"
        style="width: 282px;"
        @search="onSearch"
      >
        <a-select slot="addonBefore" v-model="searchType" style="width: 90px;">
          <a-select-option value="entity">
            实体名
          </a-select-option>
          <a-select-option value="area">
            行政区
          </a-select-option>
        </a-select>
      </a-input-search>
      <div class="close-icon" @click="closeSearch">
        <a-icon-font type="iconicon-beifen1" />
      </div>
    </div>

    <div v-if="matchedEntity.length > 0" class="search-options" @click.stop>
      <div
        v-for="(entity, index) in matchedEntity"
        :key="index"
        class="option"
        @click="clickSearchOption(entity)"
      >
        {{ entity.name }}
      </div>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * 搜索地图
 */
import { Component, Watch, Vue, Prop } from 'vue-property-decorator'
import KGraphStore from '@/store/modules/k-graph'
import Draggabilly from 'draggabilly'
import { key } from '@/components/gis/map-package/map-config'
import { cloneDeep, debounce } from 'lodash'

@Component({
  components: {},
})
export default class KGisSearch extends Vue {
  @Prop({ type: Boolean, default: false }) visible!: boolean
  @Prop({ type: Boolean, default: false }) topMargin!: boolean //  是否需要顶部margin的补偿

  public drag: any = null
  public searchKey: string = ''
  public searchType: string = 'entity'
  public matchedEntity: any = [] //  符合搜索词的实体列表
  public allEntityLayerData: any = [] //  所有的实体信息列表

  @Watch('visible', { immediate: true })
  private watchVisible(value: boolean) {
    const that = this
    if (value) {
      setTimeout(() => {
        const $overlay = document.querySelector(
          '.gis-map-component'
        ) as HTMLDivElement
        const $element = document.querySelector('.gis-search') as HTMLDivElement
        that.drag = new Draggabilly($element, {
          containment: $overlay,
          grid: [1, 1],
        })
      }, 500)
    } else {
      //  clear options when hide
      this.searchKey = ''
      this.matchedEntity = []
    }
  }
  //  TODO 在publish view 需要后的返回
  public get entityLayer() {
    return KGraphStore.entityLayer
  }

  @Watch('entityLayer', { immediate: true, deep: true })
  handleEntityLayer(newValue: any) {
    if (newValue) {
      // this.entityLayerData = cloneDeep(newValue)
      this.allEntityLayerData = cloneDeep(newValue)
    }
  }

  @Watch('searchKey')
  handleSearchKeyChange() {
    //  当搜索类型为实体名的时候，才开启searchKey改变自动搜索
    if (this.searchType !== 'area') {
      this.inputSearch()
    }
  }

  public inputSearch = debounce(() => {
    this.onSearch()
  }, 500)

  public async onSearch() {
    if (this.searchType === 'area') {
      this.searchGis()
    } else {
      this.matchedEntity = this.allEntityLayerData.filter((item: any) => {
        return item.name.includes(this.searchKey)
      })
      if (this.searchKey.length === 0) {
        this.matchedEntity = []
      }
      // this.$emit('search-entity', this.searchKey)
    }
  }

  public clickSearchOption(entity: any) {
    console.log(entity, 'okoko')
    // if (entity.hasGISInfo) {
    //   //  有地理位置信息，则定位到gis 中的实体
    //   this.$emit('search-entity', this.searchKey)
    // } else {
    //  收起命中的搜索条目
    this.matchedEntity = []
    this.$emit('open-entity', {
      id: entity.entityId,
      searchKey: this.searchKey,
    })
    // }
  }

  public async searchGis() {
    const parameters: any = {
      postStr: {
        searchWord: this.searchKey,
        searchType: '1',
        needSubInfo: false,
        needAll: false,
        needPolygon: true,
        needPre: true,
      },
      tk: key,
    }
    const response: any = await KGraphStore.searchAdministrative(parameters)
    if (response.data.returncode === '100') {
      const { bound } = response.data.data[0]
      if (bound) {
        const [lat1, lnt1, lat2, lnt2] = bound.split(',')
        const boundArray: any[] = [
          [lat1, lnt1],
          [lat2, lnt2],
        ]
        this.$emit('fit-bounds', boundArray)
      } else {
        this.$message.warning('暂时无法定位！')
      }
    } else {
      this.$message.warn(response.data.msg)
    }
  }

  public closeSearch() {
    this.searchKey = ''
    this.matchedEntity = []
    this.$emit('close-search')
  }

  public UpSysPanel() {
    //  set focus box
    KGraphStore.setFocusBoxg('sys')
  }
}
</script>

<style scoped lang="less">
.position-right {
  right: 150px;
}

.gis-search.top-margin {
  top: 39px;
}

.gis-search {
  align-items: center;
  background: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.18);
  display: flex;
  flex-direction: column;
  height: 48px;
  padding: 9px 12px;
  position: absolute;
  top: 1px;
  width: 320px;
  z-index: 800;

  .search-box {
    display: flex;
    justify-content: space-between;
  }

  .close-icon {
    align-items: center;
    border-radius: 2px;
    color: rgb(93, 99, 126);
    cursor: pointer;
    display: flex;
    font-size: 16px;
    padding: 4px;
    position: relative;
    user-select: none;
  }

  .search-options {
    background-color: #fff;
    left: 8px;
    min-width: 304px;
    position: relative;

    .option {
      border-bottom: 1px solid #e9e9e9;
      cursor: pointer;
      font-size: 16px;
      line-height: 30px;
      padding: 0 10px;

      &:hover {
        background: #f0f3ff;
      }
    }
  }
}
</style>
